import imutils.perspective
import imutils
import cv2


def projection(image):
    def Get_Outline(image):
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        blurred = cv2.GaussianBlur(gray, (5,5),0)
        edged = cv2.Canny(blurred,75,200)
        return edged

    def Get_cnt(edged):
        cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
        cnts = cnts[1] if imutils.is_cv3()  else cnts[0]
        docCnt = None

        if len(cnts) > 0:
            cnts = sorted(cnts,key=cv2.contourArea,reverse=True)
            for c in cnts:
                peri = cv2.arcLength(c,True)                   # 轮廓按大小降序排序
                approx = cv2.approxPolyDP(c, 0.02 * peri, True)  # 获取近似的轮廓
                if len(approx) == 4:                           # 近似轮廓有四个顶点
                    docCnt = approx
                    break
        return docCnt


    edged = Get_Outline(image)
    dot_count = Get_cnt(edged)
    result = imutils.perspective.four_point_transform(image, dot_count.reshape(4,2)) # 对原始图像进行四点透视变换

    return result


# projection(cv2.imread('../img/projection.jpg'))